package com.laundry.service;

import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 内存验证码服务 - 用于开发环境，替代Redis
 */
@Service
public class MemoryCodeService {
    
    private final Map<String, CodeEntry> codeStore = new ConcurrentHashMap<>();
    private final Map<String, Long> frequencyStore = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    
    /**
     * 存储验证码
     */
    public void setCode(String key, String code, long expireSeconds) {
        long expireTime = System.currentTimeMillis() + expireSeconds * 1000;
        codeStore.put(key, new CodeEntry(code, expireTime));
        
        // 定时清理过期的验证码
        scheduler.schedule(() -> codeStore.remove(key), expireSeconds, TimeUnit.SECONDS);
    }
    
    /**
     * 获取验证码
     */
    public String getCode(String key) {
        CodeEntry entry = codeStore.get(key);
        if (entry == null) {
            return null;
        }
        
        // 检查是否过期
        if (System.currentTimeMillis() > entry.expireTime) {
            codeStore.remove(key);
            return null;
        }
        
        return entry.code;
    }
    
    /**
     * 删除验证码
     */
    public void deleteCode(String key) {
        codeStore.remove(key);
    }
    
    /**
     * 检查频率限制
     */
    public boolean hasFrequencyLimit(String key) {
        Long lastTime = frequencyStore.get(key);
        if (lastTime == null) {
            return false;
        }
        
        // 检查是否在60秒内
        return System.currentTimeMillis() - lastTime < 60000;
    }
    
    /**
     * 设置频率限制
     */
    public void setFrequencyLimit(String key) {
        long currentTime = System.currentTimeMillis();
        frequencyStore.put(key, currentTime);
        
        // 60秒后自动清理
        scheduler.schedule(() -> frequencyStore.remove(key), 60, TimeUnit.SECONDS);
    }
    
    /**
     * 验证码条目
     */
    private static class CodeEntry {
        final String code;
        final long expireTime;
        
        CodeEntry(String code, long expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
    }
}
